import config from 'config.js';
import Api from 'api.js';
import util from 'util.js';
class FileUpload {
  constructor(config) {
    let optionsTarget = {
      count: 1,
      fileType: 'img',
      sizeType: ['original', 'compressed'],
      url: config.UploadFile,
      name: 'Uploadfile_File',
      formData: {
        'MemberID': wx.getStorageSync("MemberID"),
      },
      header: {
        'content-type': 'application/json',
        'Authorization': wx.getStorageSync("Authorization")
      },
      sourceType: ['album', 'camera'],
      compressed: true,
      maxDuration: 60,
      beforeUpload: function() {},
      success: function() {},
      fail: function() {}
    }
    this.options = Object.assign(optionsTarget, config)
    this.init(this.options.fileType)
  }

  init(fileType) {
    if (fileType === 'img') {
      this.chooseImage()
    } else {
      this.chooseVideo()
    }
  }

  chooseImage() {
    let _this = this
    wx.chooseImage({
      sizeType: this.options.sizeType,
      sourceType: this.options.sourceType,
      success: function(res) {
        var tempFilePaths = res.tempFilePaths
        tempFilePaths.forEach(item => {
          _this.upload(item, 1)
        })
      },
      fail: function(err) {
        _this.options.fail(err)
      }
    })
  }

  chooseVideo() {
    let _this = this
    wx.chooseVideo({
      sourceType: _this.options.sourceType,
      compressed: _this.options.compressed,
      maxDuration: _this.options.maxDuration,
      success: function(res) {
        if (res.duration < 10) {
          _this.options.beforeUpload(res)
          _this.upload(res.tempFilePath, 2)
        } else {
          wx.showModal({
            title: '提示',
            content: '请上传10秒内视频',
            showCancel: false,
            success: function(res) {

            }
          })
        }
      },
      fail: function(err) {
        _this.options.fail(err)
      }
    })
  }

  upload(item, intType) {
    let _this = this
    var formData = this.options.formData;
    if (intType == 2) {
      formData = {
        'MemberID': wx.getStorageSync("MemberID"),
        'IsVideo': 1,
      }
    }
    wx.uploadFile({
      url: this.options.url,
      filePath: item,
      name: this.options.name,
      formData: formData,
      header: this.options.header,
      success: function(res) {
        wx.hideToast();
        if (!(_this.options.success instanceof Function)) return false
        if (typeof res.data === 'string') { // 视业务情况而定
          _this.options.success(JSON.parse(res.data))
        } else {
          _this.options.success(res.data)
        }
      },
      fail: function(err) {
        _this.options.success(err)
      }
    })
  }
}

export default function viUpload(config) {
  new FileUpload(config)
}